﻿#include "itemedit.h"
#include "ui_itemedit.h"

ItemEdit::ItemEdit(QWidget *parent, const QString &table, const QString &entry) :
    BaseEditorDialog(parent),
    _table(table),
    _entry(entry),
    ui(new Ui::ItemEdit)
{
    ui->setupUi(this);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);
    ui->tableView->resizeColumnsToContents();

    updateView();
    createMenu();
}

ItemEdit::~ItemEdit()
{
    delete ui;
}

void ItemEdit::updateView()
{
    model->setTable(_table);
    model->setFilter(QString("entry = '%1'").arg(_entry));
    model->select();
}

void ItemEdit::setHeaderData()
{
    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,_category);    //category
    model->setHeaderData(2,Qt::Horizontal,_label);    //label
    model->setHeaderData(3,Qt::Horizontal,_detail);    //detail

    if(!_addition.isEmpty())
        model->setHeaderData(4,Qt::Horizontal,_addition);    //detail
    else
        ui->tableView->hideColumn(4);
    ui->tableView->hideColumn(5);       //entry
}

void ItemEdit::generateMenu()
{
    menu->addAction(QStringLiteral("撤销"),this,&ItemEdit::revert);
    menu->addAction(QStringLiteral("保存"),this,&ItemEdit::save);
    menu->addSeparator();
    menu->addAction(QStringLiteral("删除"),this,&ItemEdit::removeItem);
}

void ItemEdit::setTitle(const QString &title)
{
    this->setWindowTitle(title + QStringLiteral("-编辑器"));
}

void ItemEdit::setItemString(const QString &category, const QString &label, const QString &detail, const QString &additon)
{
    _category=category;
    _label=label;
    _detail=detail;
    _addition=additon;
}

void ItemEdit::save()
{
    model->submitAll();
    this->accept();
}

void ItemEdit::removeItem()
{
    if(ui->tableView->currentIndex().isValid())
    {
        int curRow = ui->tableView->currentIndex().row();
        model->removeRow(curRow);
    }
}
